/*
 * MIT License
 *
 * Copyright (c) 2025 Mark·虎
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package com.hsxxherp.key.support.exception;

import com.hsxxherp.key.common.exception.BusinessException;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.Locale;

/**
 * 支持国际化的业务异常类
 *
 * @author Mark·虎克（2486970363@qq.com）
 * @since 2025-01-25
 */
public class I18nBusinessException extends BusinessException {
    /**
     * 静态的消息源，用于获取国际化消息
     */
    private static MessageSource messageSource;
    /**
     * 消息键，用于从消息源中查找对应的国际化消息
     */
    private final String messageKey;
    /**
     * 消息参数数组，用于替换消息中的占位符
     */
    private Object[] args;

    /**
     * 构造函数，创建一个带有错误码和消息键的国际化业务异常实例。
     *
     * @param code       异常的错误码
     * @param messageKey 用于国际化消息的键
     */
    public I18nBusinessException(int code, String messageKey) {
        super(code, null);
        this.messageKey = messageKey;
    }

    /**
     * 构造函数，创建一个带有错误码、消息键和参数的国际化业务异常实例。
     *
     * @param code       异常的错误码
     * @param messageKey 用于国际化消息的键
     * @param args       消息参数数组
     */
    public I18nBusinessException(int code, String messageKey, Object[] args) {
        super(code, null);
        this.messageKey = messageKey;
        this.args = args;
    }

    /**
     * 设置消息源，用于国际化消息的解析。
     *
     * @param messageSource Spring 的 MessageSource 实例
     */
    public static void setMessageSource(MessageSource messageSource) {
        I18nBusinessException.messageSource = messageSource;
    }

    /**
     * 重写 getMessage 方法，根据消息键和参数获取国际化消息。
     *
     * @return 国际化的消息字符串
     */
    @Override
    public String getMessage() {
        if (messageSource == null) {
            return messageKey;
        }
        Locale locale = LocaleContextHolder.getLocale();
        return messageSource.getMessage(messageKey, args, locale);
    }
}